/**
 * Copyright (C) 2010, 2011 Neofonie GmbH
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package eu.dicodeproject.twitterstream.vectorize;

import eu.dicodeproject.analysis.lucene.IterableAnalyzer;
import eu.dicodeproject.analysis.util.Language;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Required;

/**
 * Class that creates term vectors using an analyzer.
 * @author jakob
 */
public class Vectorizer {
  //TODO consistent usage of languages as Language object or String

  /** Logger for this class. */
  private static final Logger log = LoggerFactory.getLogger(Vectorizer.class);

  /** language the language of the text; setter could be replaced by language recognition */
  private Language language;

  /** Map from language string to language-specific analyzer */
  private Map<String,Analyzer> analyzers;

  /** StandardAnalyzer instance as fallback for unknown languages */
  private StandardAnalyzer standardAnalyzer;

  /**
   * @param text the text to be vectorized
   * @return term vector
   * @throws IOException inherited from TokenStream
   */
  public Map<String,Integer> createVector(String text) throws IOException {
    Map<String,Integer> m = new HashMap<String,Integer>();
    for (String token : new IterableAnalyzer(getAnalyzer(), text)) {
      Integer count = m.get(token);
      if (count == null) {
        count = 0;
      }
      m.put(token, ++count);
    }
    return m;
  }

  private Analyzer getAnalyzer() {
    Analyzer analyzer = null;
    if (analyzers != null && language != null) {
      analyzer = analyzers.get(language.getCode());
    }
    if (analyzer == null) {
      log.info("no analyzer for language '" + language + "'; using StandardAnalyzer");
      analyzer = standardAnalyzer;
    }
    return analyzer;
  }

  public void setAnalyzers(Map<String,Analyzer> analyzers) {
    this.analyzers = analyzers;
  }

  @Required
  public void setStandardAnalyzer(StandardAnalyzer standardAnalyzer) {
    this.standardAnalyzer = standardAnalyzer;
  }

  public void setLanguage(Language language) {
    this.language = language;
  }
}
